import './HomeConfig.scss'

import { v4 } from 'uuid'
import { useRef, useState } from 'react'
import GridLayout from 'react-grid-layout'
import { useEventEmitter, useSize, useMount } from 'ahooks'
import { SaveOutlined, DeleteOutlined } from '@ant-design/icons'
import { Button, Collapse, Dropdown, Popconfirm, FloatButton, App } from 'antd'

import { DrawerBox } from '../Model'
import { Encrypt, GetIndexedDB, PutIndexedDB } from './IndexedDB'
import { ParamsMapping } from './HomeTemplate/BefaultParams'

import {
    TextTemplateA01,
    TextTemplateA02
} from './HomeTemplate/TextTemplate'
import {
    ChartTemplateA01,
    ChartTemplateA02,
    ChartTemplateA03,
    ChartTemplateA04,
    ChartTemplateA05,
    ChartTemplateA06,
    ChartTemplateA07,
    ChartTemplateA08,
    ChartTemplateA09,
    VChartTemplateA01,
    VChartTemplateA02,
    VChartTemplateA03,
    VChartTemplateA04,
    VChartTemplateA05,
    VChartTemplateA06,
    VChartTemplateA07,
} from './HomeTemplate/ChartTemplate'

export const TemplateMapping = {
    TextTemplateA01,
    ChartTemplateA01,
    ChartTemplateA02,
    ChartTemplateA03,
    ChartTemplateA04,
    ChartTemplateA05,
    ChartTemplateA06,
    ChartTemplateA07,
    ChartTemplateA08,
    ChartTemplateA09,
    VChartTemplateA01,
    VChartTemplateA02,
    VChartTemplateA03,
    VChartTemplateA04,
    VChartTemplateA05,
    VChartTemplateA06,
    VChartTemplateA07,
}

export const HomeTemplateList = ({ HomeEvent }) => {
    const items = [
        {
            key: 'text',
            label: '文字模板',
            children: (
                <>
                    <TextTemplateA01 preview HomeEvent={HomeEvent} />
                    <TextTemplateA02 preview HomeEvent={HomeEvent} />
                </>
            ),
        },
        {
            key: 'vCharts',
            label: '图例模板1',
            children: (
                <>
                    {/* <VChartTemplateA01 preview HomeEvent={HomeEvent} />
                    <VChartTemplateA02 preview HomeEvent={HomeEvent} />
                    <VChartTemplateA03 preview HomeEvent={HomeEvent} />
                    <VChartTemplateA04 preview HomeEvent={HomeEvent} />
                    <VChartTemplateA05 preview HomeEvent={HomeEvent} />
                    <VChartTemplateA06 preview HomeEvent={HomeEvent} /> */}
                </>
            )
        },
        {
            key: 'charts',
            label: '图例模板2',
            children: (
                <>
                    {/* <ChartTemplateA01 preview HomeEvent={HomeEvent} />
                    <ChartTemplateA02 preview HomeEvent={HomeEvent} />
                    <ChartTemplateA03 preview HomeEvent={HomeEvent} />
                    <ChartTemplateA04 preview HomeEvent={HomeEvent} />
                    <ChartTemplateA05 preview HomeEvent={HomeEvent} />
                    <ChartTemplateA06 preview HomeEvent={HomeEvent} />
                    <ChartTemplateA07 preview HomeEvent={HomeEvent} />
                    <ChartTemplateA08 preview HomeEvent={HomeEvent} />
                    <ChartTemplateA09 preview HomeEvent={HomeEvent} /> */}
                </>
            ),
        },
        {
            key: 'tables',
            label: '表单模板',
            children: <p>表单模板</p>,
        },
        {
            key: 'functions',
            label: '功能模板',
            children: <p>功能模板</p>,
        },
    ];

    return (
        <div className='HomeTemplateList'>
            <Collapse defaultActiveKey={['text', 'vCharts', 'charts', 'tables', 'functions']} ghost items={items} />
        </div>
    )
}

export const HomeRenderConfig = ({ HomeEvent, PageEvent }) => {

    const { message } = App.useApp()

    const GridBox = useRef()
    const size = useSize(GridBox)
    const [OptionsCall, setOptionsCall] = useState()

    const [DragTemp, setDragTemp] = useState()
    const [LayoutTemp, setLayoutTemp] = useState([])
    const [HomeTempConfig, setHomeTempConfig] = useState({})
    HomeEvent.useSubscription(val => setDragTemp(val))
    const onDrop = (e) => {
        const { x, y } = e.at(-1)
        const { i, ...temp } = DragTemp
        const newI = `${i}__${v4()}`
        const tempData = { i: newI, x, y, ...temp }

        if (i.includes('VChartTemplate')) {
            const filteredKeys = Object.keys(ParamsMapping).filter(key => key.includes(i))
            const data = filteredKeys.reduce((acc, key) => {
                acc[key] = ParamsMapping[key]
                return acc
            }, {})
            setHomeTempConfig({ ...HomeTempConfig, [newI]: data })
        } else {
            setHomeTempConfig({ ...HomeTempConfig, [newI]: ParamsMapping[i] })
        }

        setLayoutTemp([...LayoutTemp, tempData])
        setDragTemp()
    }

    const TemplateDelete = (i) => {
        const data = LayoutTemp.filter(v => v.i !== i)
        delete HomeTempConfig[i]
        setLayoutTemp([...data])
        setHomeTempConfig({ ...HomeTempConfig })
    }

    const ModifyTemplate = (i) => {
        const [tempName] = i.split('__')
        setOptionsCall({
            title: '组件设置',
            type: 'HomeTempConfig',
            placement: 'left',
            data: { i, type: tempName, params: HomeTempConfig[i] }
        })
    }

    const ModifyVChartTemplate = (i, type) => {
        const [tempName] = i.split('__')
        const combination = tempName + type
        const Mapping = {
            Common: '基础设置',
            Title: '标题设置',
            Axes: '轴线设置',
            Legends: '图例设置',
            Label: '标签设置',
            Tooltip: '提示设置',
            Crosshair: '指示设置',
            TotalLabel: '合计设置',
            MarkLine: '标注线设置',
            MarkPoint: '标注点设置',
            ScrollBar: '滚动条设置',
            Line: '折线设置',
            LineLabel: '折线标签设置',
            Point: '图元设置',
            Bar: '柱图设置',
            BarBack: '柱图背景设置',
        }

        setOptionsCall({
            title: Mapping[type],
            type: 'HomeTempConfig',
            placement: 'left',
            data: { i, type: combination, params: HomeTempConfig[i][combination] }
        })
    }

    const items = (i) => {
        const VChartStart = i.includes('VChartTemplate')
        const VChartTemplateA01 = i.includes('VChartTemplateA01')
        const VChartTemplateA02 = i.includes('VChartTemplateA02')
        const VChartTemplateA03 = i.includes('VChartTemplateA03')
        const VChartTemplateA04 = i.includes('VChartTemplateA04')
        const VChartTemplateA05 = i.includes('VChartTemplateA05')
        const VChartTemplateA06 = i.includes('VChartTemplateA06')

        return ([
            // Todo     一号版设置
            VChartTemplateA01 && {
                key: 'VChartIndependent',
                type: 'group',
                label: '独立设置',
                children: [
                    {
                        key: 'Common',
                        label: (<Button type='link' onClick={() => ModifyVChartTemplate(i, 'Common')}>基础设置</Button>)
                    },
                    {
                        key: 'Title',
                        label: (<Button type='link' onClick={() => ModifyVChartTemplate(i, 'Title')}>标题设置</Button>)
                    },
                    {
                        key: 'TotalLabel',
                        label: (<Button type='link' onClick={() => ModifyVChartTemplate(i, 'TotalLabel')}>合计信息</Button>)
                    },
                    {
                        key: 'MarkLine',
                        label: (<Button type='link' onClick={() => ModifyVChartTemplate(i, 'MarkLine')}>标注线</Button>)
                    },
                    {
                        key: 'MarkPoint',
                        label: (<Button type='link' onClick={() => ModifyVChartTemplate(i, 'MarkPoint')}>标注点</Button>)
                    },
                    {
                        key: 'ScrollBar',
                        label: (<Button type='link' onClick={() => ModifyVChartTemplate(i, 'ScrollBar')}>滚动条</Button>)
                    },
                ]
            },
            VChartTemplateA01 && {
                key: 'VChartOverall',
                label: '全局设置',
                children: [
                    {
                        key: 'Axes',
                        label: (<Button type='link' onClick={() => ModifyVChartTemplate(i, 'Axes')}>轴线设置</Button>)
                    },
                    {
                        key: 'Legends',
                        label: (<Button type='link' onClick={() => ModifyVChartTemplate(i, 'Legends')}>图例设置</Button>)
                    },
                    {
                        key: 'Label',
                        label: (<Button type='link' onClick={() => ModifyVChartTemplate(i, 'Label')}>标签设置</Button>)
                    },
                    {
                        key: 'Tooltip',
                        label: (<Button type='link' onClick={() => ModifyVChartTemplate(i, 'Tooltip')}>提示设置</Button>)
                    },
                    {
                        key: 'Crosshair',
                        label: (<Button type='link' onClick={() => ModifyVChartTemplate(i, 'Crosshair')}>指示设置</Button>)
                    },
                ]
            },
            VChartTemplateA01 && {
                key: 'VChartA01Line',
                label: '图元设置',
                children: [
                    {
                        key: 'Line',
                        label: (<Button type='link' onClick={() => ModifyVChartTemplate(i, 'Line')}>折线设置</Button>)
                    },
                    {
                        key: 'LineLabel',
                        label: (<Button type='link' onClick={() => ModifyVChartTemplate(i, 'LineLabel')}>折线标签</Button>)
                    },
                    {
                        key: 'Point',
                        label: (<Button type='link' onClick={() => ModifyVChartTemplate(i, 'Point')}>图元信息</Button>)
                    },
                    {
                        key: 'Bar',
                        label: (<Button type='link' onClick={() => ModifyVChartTemplate(i, 'Bar')}>柱图设置</Button>)
                    },
                    {
                        key: 'BarBack',
                        label: (<Button type='link' onClick={() => ModifyVChartTemplate(i, 'BarBack')}>柱图背景</Button>)
                    },
                ]
            },
            // Todo     二号版设置
            VChartTemplateA02 && {
                key: 'VChartIndependentA02',
                type: 'group',
                label: '独立设置',
                children: [
                    {
                        key: 'Common',
                        label: (<Button type='link' onClick={() => ModifyVChartTemplate(i, 'Common')}>基础设置</Button>)
                    },
                    {
                        key: 'Title',
                        label: (<Button type='link' onClick={() => ModifyVChartTemplate(i, 'Title')}>标题设置</Button>)
                    },
                ]
            },
            VChartTemplateA02 && {
                key: 'VChartOverallA02',
                label: '全局设置',
                children: [
                    {
                        key: 'Axes',
                        label: (<Button type='link' onClick={() => ModifyVChartTemplate(i, 'Axes')}>轴线设置</Button>)
                    },
                    {
                        key: 'Legends',
                        label: (<Button type='link' onClick={() => ModifyVChartTemplate(i, 'Legends')}>图例设置</Button>)
                    },
                    {
                        key: 'Label',
                        label: (<Button type='link' onClick={() => ModifyVChartTemplate(i, 'Label')}>标签设置</Button>)
                    },
                    {
                        key: 'Tooltip',
                        label: (<Button type='link' onClick={() => ModifyVChartTemplate(i, 'Tooltip')}>提示设置</Button>)
                    },
                    {
                        key: 'Crosshair',
                        label: (<Button type='link' onClick={() => ModifyVChartTemplate(i, 'Crosshair')}>指示设置</Button>)
                    },
                ]
            },
            VChartTemplateA02 && {
                key: 'VChartA02Line',
                label: '图元设置',
                children: [
                    {
                        key: 'Line',
                        label: (<Button type='link' onClick={() => ModifyVChartTemplate(i, 'Line')}>折线设置</Button>)
                    },
                    {
                        key: 'Point',
                        label: (<Button type='link' onClick={() => ModifyVChartTemplate(i, 'Point')}>图元设置</Button>)
                    },
                    {
                        key: 'Pie',
                        label: (<Button type='link' onClick={() => ModifyVChartTemplate(i, 'Pie')}>饼图设置</Button>)
                    },
                    {
                        key: 'Indicator',
                        label: (<Button type='link' onClick={() => ModifyVChartTemplate(i, 'Indicator')}>指标卡设置</Button>)
                    },
                ]
            },
            // Todo     三号版
            VChartTemplateA03 && {
                key: 'VChartIndependentA03',
                type: 'group',
                label: '仪表盘设置',
                children: [
                    {
                        key: 'Common',
                        label: (<Button type='link' onClick={() => ModifyVChartTemplate(i, 'Common')}>基础设置</Button>)
                    },
                    {
                        key: 'Title',
                        label: (<Button type='link' onClick={() => ModifyVChartTemplate(i, 'Title')}>标题设置</Button>)
                    },
                    {
                        key: 'Circular',
                        label: (<Button type='link' onClick={() => ModifyVChartTemplate(i, 'Circular')}>循环样式</Button>)
                    },
                    {
                        key: 'Gauge',
                        label: (<Button type='link' onClick={() => ModifyVChartTemplate(i, 'Gauge')}>测量样式</Button>)
                    },
                ]
            },
            VChartTemplateA03 && {
                key: 'VChartA03Poin',
                label: '图元设置',
                children: [
                    {
                        key: 'Pin',
                        label: (<Button type='link' onClick={() => ModifyVChartTemplate(i, 'Pin')}>指针前景</Button>)
                    },
                    {
                        key: 'Pointer',
                        label: (<Button type='link' onClick={() => ModifyVChartTemplate(i, 'Pointer')}>指针图元</Button>)
                    },
                    {
                        key: 'PinBackground',
                        label: (<Button type='link' onClick={() => ModifyVChartTemplate(i, 'PinBackground')}>指针底盘</Button>)
                    },
                    {
                        key: 'Indicator',
                        label: (<Button type='link' onClick={() => ModifyVChartTemplate(i, 'Indicator')}>指标卡设置</Button>)
                    },
                ]
            },
            // Todo     四号版
            VChartTemplateA04 && {
                key: 'VChartIndependentA04',
                type: 'group',
                label: '进度图设置',
                children: [
                    {
                        key: 'Common',
                        label: (<Button type='link' onClick={() => ModifyVChartTemplate(i, 'Common')}>基础设置</Button>)
                    },
                    {
                        key: 'Title',
                        label: (<Button type='link' onClick={() => ModifyVChartTemplate(i, 'Title')}>标题设置</Button>)
                    },
                ]
            },
            VChartTemplateA04 && {
                key: 'VChartOverallA04',
                label: '全局设置',
                children: [
                    {
                        key: 'Axes',
                        label: (<Button type='link' onClick={() => ModifyVChartTemplate(i, 'Axes')}>轴线设置</Button>)
                    },
                    {
                        key: 'Legends',
                        label: (<Button type='link' onClick={() => ModifyVChartTemplate(i, 'Legends')}>图例设置</Button>)
                    },
                    {
                        key: 'Tooltip',
                        label: (<Button type='link' onClick={() => ModifyVChartTemplate(i, 'Tooltip')}>提示设置</Button>)
                    },
                ]
            },
            VChartTemplateA04 && {
                key: 'VChartA04Poin',
                label: '图元设置',
                children: [
                    {
                        key: 'Progress',
                        label: (<Button type='link' onClick={() => ModifyVChartTemplate(i, 'Progress')}>图元设置</Button>)
                    },
                    {
                        key: 'Tooltip',
                        label: (<Button type='link' onClick={() => ModifyVChartTemplate(i, 'Tooltip')}>提示设置</Button>)
                    },
                    {
                        key: 'Indicator',
                        label: (<Button type='link' onClick={() => ModifyVChartTemplate(i, 'Indicator')}>指标卡设置</Button>)
                    },
                ]
            },
            // Todo     五号版
            VChartTemplateA05 && {
                key: 'VChartIndependentA05',
                type: 'group',
                label: '水波图设置',
                children: [
                    {
                        key: 'Common',
                        label: (<Button type='link' onClick={() => ModifyVChartTemplate(i, 'Common')}>基础设置</Button>)
                    },
                    {
                        key: 'Title',
                        label: (<Button type='link' onClick={() => ModifyVChartTemplate(i, 'Title')}>标题设置</Button>)
                    },
                    {
                        key: 'Tooltip',
                        label: (<Button type='link' onClick={() => ModifyVChartTemplate(i, 'Tooltip')}>提示设置</Button>)
                    },
                    {
                        key: 'Indicator',
                        label: (<Button type='link' onClick={() => ModifyVChartTemplate(i, 'Indicator')}>指标卡设置</Button>)
                    },
                ]
            },
            // Todo     六号版
            VChartTemplateA06 && {
                key: 'VChartIndependent6',
                type: 'group',
                label: '独立设置',
                children: [
                    {
                        key: 'Common',
                        label: (<Button type='link' onClick={() => ModifyVChartTemplate(i, 'Common')}>基础设置</Button>)
                    },
                    {
                        key: 'Title',
                        label: (<Button type='link' onClick={() => ModifyVChartTemplate(i, 'Title')}>标题设置</Button>)
                    }
                ]
            },
            VChartTemplateA06 && {
                key: 'VChartOverall6',
                label: '全局设置',
                children: [
                    {
                        key: 'Axes',
                        label: (<Button type='link' onClick={() => ModifyVChartTemplate(i, 'Axes')}>轴线设置</Button>)
                    },
                    {
                        key: 'Legends',
                        label: (<Button type='link' onClick={() => ModifyVChartTemplate(i, 'Legends')}>图例设置</Button>)
                    },
                    {
                        key: 'Label',
                        label: (<Button type='link' onClick={() => ModifyVChartTemplate(i, 'Label')}>标签设置</Button>)
                    },
                    {
                        key: 'Tooltip',
                        label: (<Button type='link' onClick={() => ModifyVChartTemplate(i, 'Tooltip')}>提示设置</Button>)
                    },
                ]
            },
            VChartTemplateA06 && {
                key: 'VChartA01Line',
                label: '图元设置',
                children: [
                    {
                        key: 'Line',
                        label: (<Button type='link' onClick={() => ModifyVChartTemplate(i, 'Line')}>折线设置</Button>)
                    },
                    {
                        key: 'LineLabel',
                        label: (<Button type='link' onClick={() => ModifyVChartTemplate(i, 'LineLabel')}>折线标签</Button>)
                    },
                    {
                        key: 'Point',
                        label: (<Button type='link' onClick={() => ModifyVChartTemplate(i, 'Point')}>图元信息</Button>)
                    },
                ]
            },


            !VChartStart && {
                key: 'Other',
                type: 'group',
                label: '其他设置',
                children: [
                    {
                        key: 1,
                        label: (
                            <Button type='link' onClick={() => ModifyTemplate(i)}>编辑</Button>
                        )
                    },
                ]
            },
            {
                key: 'options',
                type: 'group',
                label: '其他操作',
                children: [
                    {
                        key: 'delete',
                        label: (
                            <Popconfirm title="删除提醒!" description="删除后将不可恢复,是否要继续删除?" onConfirm={() => TemplateDelete(i)} okText="删除" cancelText="取消">
                                <Button type='link' danger>删除</Button>
                            </Popconfirm>
                        )
                    }
                ]
            },
        ])
    }
    const ModalEvent = useEventEmitter()
    ModalEvent.useSubscription(val => {
        const { type, data } = val
        if (type === 'formBack') {
            const { formItem, ...params } = data
            if (formItem.includes('VChart')) HomeTempConfig[params.i][formItem] = params
            else HomeTempConfig[data.i] = params
            setHomeTempConfig({ ...HomeTempConfig })
            setTimeout(() => ModalEvent.emit({ type: 'offLoading' }), 500)
        }
    })
    const onSave = async () => {
        const data = { LayoutTemp, HomeTempConfig }
        console.log(data)
        console.log('保存布局', await Encrypt(data))
        await PutIndexedDB('home', data)
        PageEvent.emit({ type: 'updataHome' })
        message.success('首页更新成功!')
    }
    const onClear = () => {
        setLayoutTemp([])
        setHomeTempConfig({})
    }
    useMount(async () => {
        const { HomeTempConfig, LayoutTemp } = await GetIndexedDB('home')
        setLayoutTemp(LayoutTemp)
        setHomeTempConfig(HomeTempConfig)
    })
    return (
        <div className='HomeRenderConfig' ref={GridBox}>
            {size &&
                <GridLayout
                    className="Layout"
                    layout={LayoutTemp}
                    isDroppable={true}
                    isResizable={true}
                    margin={[1, 1]}
                    cols={12}
                    rowHeight={size.height / 12}
                    width={size.width}
                    onResizeStop={e => setLayoutTemp(e)}
                    onDragStop={e => setLayoutTemp(e)}
                    onDrop={onDrop}
                >
                    {LayoutTemp.map(({ i }) => {
                        const [tempName] = i.split('__')
                        const Template = TemplateMapping[tempName]
                        const config = HomeTempConfig[i]
                        return (
                            <div key={i}>
                                <Dropdown menu={{ items: items(i) }} trigger={['contextMenu']}>
                                    <div style={{ width: '100%', height: '100%' }}>
                                        <Template key={new Date().getTime()} config={config} />
                                    </div>
                                </Dropdown>
                            </div>
                        )
                    })}
                </GridLayout>
            }
            {LayoutTemp.length !== 0 &&
                <FloatButton.Group
                    shape="square"
                    style={{
                        right: 48,
                    }}
                >
                    <FloatButton
                        icon={<SaveOutlined />}
                        tooltip='保存布局'
                        type='primary'
                        onClick={onSave}
                    />

                    <Popconfirm
                        title="操作警告!"
                        description="是否要删除已配置好的布局?"
                        onConfirm={onClear}
                        okText="清空"
                        cancelText="取消"
                    >
                        <FloatButton icon={<DeleteOutlined />} tooltip='清空布局' />
                    </Popconfirm>

                </FloatButton.Group>
            }
            <DrawerBox OptionsCall={OptionsCall} ModalEvent={ModalEvent} />
        </div >
    )
}